<?php

/**
 * @author Nguyen Duc Thuan <me@ndthuan.com>
 * @copyright Nguyen Duc Thuan <me@ndthuan.com>
 */
class Fete_Exception extends Exception
{

    /**
     *
     * Register exception handler
     */
    static public function registerExceptionHandler()
    {
        set_exception_handler(array(__CLASS__, 'handleException'));
        set_error_handler(array(__CLASS__, 'handleError'));
    }

    static public function unregisterExceptionHandler()
    {
        restore_error_handler();
        restore_exception_handler();
    }

    static public function handleException(Exception $e)
    {
        try {
            ob_end_clean();
        } catch (Exception $e) {}

        if ('production' === Fete_Registry::getInstance()->get(
            'FETE_ENV',
            'production')) {

            if (404 === $e->getCode()) {
                header('HTTP/1.0 404 Not Found');
                echo '<h1>An Error Occured</h1><h2>Page Not Found</h2>';
            } else {
                header('HTTP/1.0 500 Internal Server Error');
                echo '<h1>An Error Occured</h1><h2>Application Error</h2>';
            }
        } else {
            echo $e->getMessage(), '<br />', nl2br($e->getTraceAsString());
        }
        exit;
    }

    static public function handleError($errno, $errstr, $errfile, $errline)
    {
        try {
            ob_end_clean();
        } catch (Exception $e) {}

        if ('production' === Fete_Registry::getInstance()->get(
            'FETE_ENV'
            , 'production')) {
            header('HTTP/1.0 500 Internal Server Error');
            echo '<h1>An Error Occured</h1><h2>Application Error</h2>';
        } else {
            echo $errstr, '<br />';
            $e = new Exception();
            echo nl2br($e->getTraceAsString());
        }
        return true;
        exit;
    }
}
